// pages/publishdetail/publishdetail.js
//获取应用实例
var app = getApp();
var model = require('../../utils/model/model.js');
//引用
var fileData = require('../../utils/data.js');
var util = require('../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // advert_url: fileData.getAdvertData(),
    formlist: [],
    userInfo: '',
    title: '',
    keys: '',
    otherData: [{ txt: '无行李', checked: false }, { txt: '行李多', checked: false }, { txt: '晕车', checked: false },
    { txt: '不抽烟', checked: false }, { txt: '抽烟', checked: false }, { txt: '会开车', checked: false },
    { txt: '赶时间', checked: false }, { txt: '不赶时间', checked: false }, { txt: '男司机', checked: false },
    { txt: '女司机', checked: false }, { txt: '带小孩', checked: false }
    ],
    canSubmit: false,
    formData: {
      type: '',
      userId: '',
      placeFrom: '',
      placeTo: '',
      beginTime: '',
      beginDate: '',
      contacts: '',
      contactNum: '',
      demand: '',
      labelArray: '',
    },
    modelData: {
      showModal: false,
      signle: true,
      signleBtnTxt: "确定",
      content: '',
    },
    value: '',
    currentInput: {},
    active: '',
    isAgree: false,
    typeObj: { '1': '车找人', '2': '人找车', '3': '货找车', '4': '车找货' },
    type: '1'
  },
  checkboxChange: function (e) {
  },
  openText: function (e) {//打开《拼车平台声明》
    this.data.formData.label = this.data.type;
    // wx.setStorage({
    //   key: 'carPublish',
    //   data: this.formData,
    // })
    wx.navigateTo({
      url: '/pages/text/text?type=1',
    })
  },
  bindPickerChange: function (e) {//下拉框事件
    var item = e.target.dataset.item;
    if (e.target.dataset.type != undefined) {
      if (item.key=='beginDate'){
        if (e.detail.value == item.start){
          var date = app.formDate(new Date()).split(' ');
          if(this.data.type=='1'||this.data.type=='4'){
            this.setData({
              ['formlist[4].start']: date[1]
            })
          }else{
            this.setData({
              ['formlist[3].start']: date[1]
            })
          }
        }else{
          if (this.data.type == '1' || this.data.type == '4') {
            this.setData({
              ['formlist[4].start']: ''
            })
          } else {
            this.setData({
              ['formlist[3].start']: ''
            })
          }
        }
      }
      this.data.formData[item.key] = e.detail.value;
    }else{
      this.data.formData[item.key] = item.data[e.detail.value];
    }
    this.setData({
      formData: this.data.formData
    });
    this.changeValue();
  },
  selOther(e) {//选择其他需求事件
    var label_arry = [];
    var index = e.target.dataset.index;
    if (this.data.otherData[index].checked == false) {
      this.data.otherData.forEach(function (ele) {
        if (ele.checked == true) {
          label_arry.push(ele.txt);
        }
      })
      if (label_arry.length >= 4) {
        wx.showModal({
          title: '提示',
          showCancel:false,
          content: '最多只能选择四个',
          success: function (res) {
            if (res.confirm) {

            }
          }
        })
      } else {

        this.data.otherData[index].checked = !this.data.otherData[index].checked;
        this.setData({
          otherData: this.data.otherData
        });
      }
    } else {
      this.data.otherData[index].checked = !this.data.otherData[index].checked;
      this.setData({
        otherData: this.data.otherData
      });
    }

    // this.data.formlist[7].otherData = this.data.otherData;
    this.changeValue();
  },
  changeTextarea: function (e) {//其他需求textarea值改变事件
    var key = e.target.dataset.value;
    if (key == 'isAgree') {
      if (e.detail.value.length > 0) {
        this.data.isAgree = true;
      } else {
        this.data.isAgree = false;
      }
    } else if (key == 'saleRemain'){
      this.data.formData[key] = e.detail.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
    } else {
      this.data.formData[key] = e.detail.value;
    }
    this.setData({
      formData: this.data.formData,
      isAgree: this.data.isAgree
    })
    this.changeValue();
  },
  changeValue() {
    var flag = true;
    var item = this.data.formData;
    if (this.data.type == '2') {
      if ((item.placeFrom == '') || (item.placeTo == '') || (item.beginTime == '') || (item.beginDate == '') || (item.wantNum == '') || (item.contacts == '') || (item.contactNum == '') || (this.data.isAgree == false)) {
        flag = false;
      }
    } else if (this.data.type == '1') {
      if ((item.placeFrom == '') || (item.placeTo == '') || (item.beginTime == '') || (item.beginDate == '') || (item.afterPath == '') || (item.goNum == '') || (item.saleRemain == '') || (item.contacts == '') || (item.contactNum == '') || (this.data.isAgree == false)) {
        flag = false;
      }
    } else if (this.data.type == '3') {
      if ((item.placeFrom == '') || (item.placeTo == '') || (item.beginTime == '') || (item.beginDate == '') || (item.goodsWeight == '') || (item.goodsVolume == '') || (item.goodsSize == '') || (item.contacts == '') || (item.contactNum == '') || (this.data.isAgree == false)) {
        flag = false;
      }
    } else {
      if ((item.placeFrom == '') || (item.placeTo == '') || (item.beginTime == '') || (item.beginDate == '') || (item.afterPath == '') || (item.carType == '') || (item.carSize == '') || (item.saleRemain == '') || (item.contacts == '') || (item.contactNum == '') || (this.data.isAgree == false)) {
        flag = false;
      }
    }
    this.setData({
      canSubmit: flag
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    this.setData({
      userInfo: JSON.parse(wx.getStorageSync('userInfo'))
    })
    model.init.apply(this, ['modelData']);
    var date = app.formDate(new Date()).split(' ');
    wx.setNavigationBarTitle({
      title: this.data.typeObj[options.label]
    })
    if (options.label) {
      this.data.type = options.label;
    }
    if (this.data.type == '2' || this.data.type == '1'){
      wx.request({
        url: app.globalData.httpApiCar + 'labInfo/all', //仅为示例，并非真实的接口地址
        data: {
          type: this.data.type
        },
        success: function (res) {
          if (res.data.success) {
            res.data.data.forEach(function (ele) {
              ele.txt = ele.labName;
              ele.checked = false;
            })
            that.setData({ otherData: res.data.data})
          }
        }
      })
    }
    var formlist = [];
    var formData = {};
    if (this.data.type == '2') {
      formData = {
        placeFrom: '',
        placeTo: '',
        beginDate: '',
        beginTime: '',
        wantNum: '',
        contacts: '',
        contactNum: '',
        demand: ''
      };
      formlist = [
        { isrequire: true, label: '出发地', valueType: 'text', key: 'placeFrom', tips: '请输入出发地', type: 'input', icon: "blue icon-chufadimudedi" },
        { isrequire: true, label: '目的地', valueType: 'text', key: 'placeTo', tips: '请输入目的地', type: 'input', icon: "icon-chufadimudedi" },
        { isrequire: true, label: '出发日期', valueType: 'text', key: 'beginDate', tips: '请选择出发日期', start: date[0], type: 'select', mode: 'date', icon: "color9 icon-shijian" },
        { isrequire: true, label: '出发时间', valueType: 'text', key: 'beginTime', tips: '请选择出发时间', start: date[1], type: 'select', mode: 'time', icon: "color9 icon-shijian" },
        { isrequire: true, label: '乘车人数', maxlength: 3, valueType: 'number', key: 'wantNum', tips: '请输入人数', type: 'input', icon: "color9 icon-renshu" },
        { isrequire: true, label: '联系人', valueType: 'text', key: 'contacts', tips: '请选择', type: 'input', mode: 'date', icon: "color9 icon-lianxiren" },
        { isrequire: true, label: '手机号', maxlength: 11, valueType: 'number', key: 'contactNum', tips: '请填写', type: 'input', icon: "color9 icon-shoujihao", reg: "^1[34578][0-9]{9}$" }
      ];
    } else if (this.data.type == '1') {
      formData = {
        placeFrom: '',
        placeTo: '',
        beginTime: '',
        beginDate: '',
        afterPath: '',
        goNum: '',
        saleRemain: '',
        contacts: '',
        contactNum: '',
        demand: ''
      };
      formlist = [
        { isrequire: true, label: '出发地', valueType: 'text', key: 'placeFrom', tips: '请输入出发地', type: 'input', icon: "blue icon-chufadimudedi" },
        { isrequire: true, label: '目的地', valueType: 'text', key: 'placeTo', tips: '请输入目的地', type: 'input', icon: "icon-chufadimudedi" },
        { isrequire: true, label: '途经地', valueType: 'text', key: 'afterPath', tips: '请输入目的地', type: 'input', icon: "color9  icon-tujingdi" },
        { isrequire: true, label: '出发日期', valueType: 'text', key: 'beginDate', tips: '请选择出发日期', start: date[0], type: 'select', mode: 'date', icon: "color9 icon-shijian" },
        { isrequire: true, label: '出发时间', valueType: 'text', key: 'beginTime', tips: '请选择出发时间', start: date[1], type: 'select', mode: 'time', icon: "color9 icon-shijian" },
        { isrequire: true, label: '可乘人数', maxlength: 3, valueType: 'number', key: 'goNum', tips: '请输入乘客数', type: 'input', icon: "color9 icon-renshu" },
        { isrequire: true, label: '车费', valueType: 'digit', key: 'saleRemain', tips: '请输入价格，单位每人次', type: 'input', icon: "color9  icon-jine" },
        { isrequire: true, label: '联系人', valueType: 'text', key: 'contacts', tips: '联系人', type: 'input', mode: 'date', icon: "color9 icon-lianxiren" },
        { isrequire: true, label: '手机号', maxlength: 11, valueType: 'number', key: 'contactNum', tips: '请填写', type: 'input', icon: "color9 icon-shoujihao", reg: "^1[34578][0-9]{9}$" }
      ];
    } else if (this.data.type == "3") {
      formData = {
        placeFrom: '',
        placeTo: '',
        beginTime: '',
        beginDate: '',
        goodsWeight: '',
        goodsVolume: '',
        goodsSize: '',
        contacts: '',
        contactNum: '',
        demand: ''
      };
      formlist = [
        { isrequire: true, label: '出发地', valueType: 'text', key: 'placeFrom', tips: '请输入出发地', type: 'input', icon: "blue icon-chufadimudedi" },
        { isrequire: true, label: '目的地', valueType: 'text', key: 'placeTo', tips: '请输入目的地', type: 'input', icon: "icon-chufadimudedi" },
        { isrequire: true, label: '出发日期', valueType: 'text', key: 'beginDate', tips: '请选择出发日期', start: date[0], type: 'select', mode: 'date', icon: "color9 icon-shijian" },
        { isrequire: true, label: '出发时间', valueType: 'text', key: 'beginTime', tips: '请选择出发时间', start: date[1], type: 'select', mode: 'time', icon: "color9 icon-shijian" },
        { isrequire: true, label: '货物尺寸', valueType: 'text', key: 'goodsSize', tips: '请输入货物尺寸，单位米', type: 'input', icon: "color9  icon-cheliangchicun" },
        { isrequire: true, label: '货物重量', valueType: 'text', key: 'goodsWeight', tips: '请输入货物重量，单位公斤', type: 'input', icon: "color9  icon-huowuzhongliang" },
        { isrequire: true, label: '货物体积', valueType: 'text', key: 'goodsVolume', tips: '请输入货物体积，单位立方米', type: 'input', icon: "color9  icon-huowutiji" },
        { isrequire: true, label: '联系人', valueType: 'text', key: 'contacts', tips: '联系人', type: 'input', mode: 'date', icon: "color9 icon-lianxiren" },
        { isrequire: true, label: '手机号', maxlength: 11, valueType: 'number', key: 'contactNum', tips: '请填写', type: 'input', icon: "color9 icon-shoujihao", reg: "^1[34578][0-9]{9}$" }
      ];
    } else {
      formData = {
        placeFrom: '',
        placeTo: '',
        afterPath: '',
        beginTime: '',
        beginDate: '',
        carType: '',
        carSize: '',
        carWeight:'',
        contacts: '',
        saleRemain: '',
        contactNum: '',
        demand: ''
      };
      formlist = [
        { isrequire: true, label: '出发地', valueType: 'text', key: 'placeFrom', tips: '请输入出发地', type: 'input', icon: "blue icon-chufadimudedi" },
        { isrequire: true, label: '目的地', valueType: 'text', key: 'placeTo', tips: '请输入目的地', type: 'input', icon: "icon-chufadimudedi" },
        { isrequire: true, label: '途经地', valueType: 'text', key: 'afterPath', tips: '请输入途经地', type: 'input', icon: "color9  icon-tujingdi" },
        { isrequire: true, label: '出发日期', valueType: 'text', key: 'beginDate', tips: '请选择出发日期', start: date[0], type: 'select', mode: 'date', icon: "color9 icon-shijian" },
        { isrequire: true, label: '出发时间', valueType: 'text', key: 'beginTime', tips: '请选择出发时间', start: date[1], type: 'select', mode: 'time', icon: "color9 icon-shijian" },
        { isrequire: true, label: '车辆类型', valueType: 'text', key: 'carType', tips: '请选择车辆类型', icon: "color9  icon-cheliangshuliang", type: 'select', data: ['微型货车（GA≤1.8吨）', '轻型货车（1.8吨＜GA≤6吨）', '中型货车（6.0吨＜GA≤14吨）', '重型货车（GA＞14吨）', '轻型半挂车（GA≤7.1吨）', '中型半挂车（7.1吨＜GA≤19.5吨）', '重型半挂车（19.5＜GA≤34吨）','超重型半挂车（GA＞34吨）']},
        { isrequire: true, label: '车辆尺寸', valueType: 'text', key: 'carSize', tips: '请输入车辆尺寸，单位米', type: 'input', icon: "color9  icon-cheliangchicun" },
        { isrequire: true, label: '车辆容量', valueType: 'text', key: 'carWeight', tips: '请输入车辆容量，单位公斤', type: 'input', icon: "color9  icon-huowuzhongliang" },
        { isrequire: true, label: '金额', valueType: 'digit', key: 'saleRemain', tips: '请输入金额', type: 'input', icon: "color9  icon-jine" },
        { isrequire: true, label: '联系人', valueType: 'text', key: 'contacts', tips: '联系人', type: 'input', mode: 'date', icon: "color9 icon-lianxiren" },
        { isrequire: true, label: '手机号', maxlength: 11, valueType: 'number', key: 'contactNum', tips: '请填写', type: 'input', icon: "color9 icon-shoujihao", reg: "^1[34578][0-9]{9}$" }
      ];

    }
    this.setData({
      formlist: formlist,
      formData: formData,
      type: this.data.type
    })
  },
  checkReg:function(data){
    var flag=true;
    for (var i = 0; i < data.length;i++){
      if (data[i].reg) {
        var reg = new RegExp(data[i].reg);
        if (!reg.test(this.data.formData[data[i].key])) {
          flag = false;
          wx.showModal({
            title: '提示',
            content: '请输入正确的' + data[i].label,
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
              }
            }
          })
          return;
        }
      }
    }
    return flag;
  },
  save: function (e) {//保存按钮
    var that = this;
    var label_arry = [];
    this.data.otherData.forEach(function (ele) {
      if (ele.checked == true) {
        label_arry.push(ele.txt);
      }
    })
    if (this.data.canSubmit) {
      this.setData({
        canSubmit:false
      });
      if(this.checkReg(this.data.formlist)==true){
      var param={};
      for (var j in this.data.formData) {
        if (j != 'beginDate' && j !='beginTime') {
          param[j] = this.data.formData[j];
        }
      }
      param.userId= this.data.userInfo.id;
      param.type=this.data.type;
      param.backupA = this.data.formData.beginDate + ' ' + this.data.formData.beginTime + ':00';
      if (this.data.type == '1' || this.data.type == '2') {
        param.labelArray = label_arry.join('/');
      }
      if (that.data.type == '1' || that.data.type == '4') {
        wx.showModal({
          title: '提示',
          content: '需要支付20%的保证金，确定发布吗？',
          success: function (res) {
            if (res.confirm) {
              that.pulish(param);
            }
          }
        })
      }else{
        that.pulish(param);
      }
        
    }
    };
  },
  pulish: function (param){
    var that=this;
    wx.request({
      url: app.globalData.httpApiCar + 'freeRideInfo/save', //仅为示例，并非真实的接口地址
      data: param,
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: function (res) {
        if (res.data.success) {

          if (that.data.type == '1' || that.data.type == '4') {
            that.payMoney(res.data.data);
          } else {
            wx.setStorage({
              key: 'url',
              data: '/pages/freeRideHome/freeRideHome',
            })
            wx.redirectTo({
              url: '/pages/regsuccess/regsuccess?btnText=返回首页&showText=发布成功'
            })
          }
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.error,
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                that.setData({
                  canSubmit: true
                })
              }
            }
          })
        }
      }
    })
  },
  payMoney:function(item){
    var that = this;
    wx.request({
      url: app.globalData.httpApiCar + 'freeRideInfo/releaseMarginPayment', //仅为示例，并非真实的接口地址
      data: {
        openId: app.globalData.openId,
        type:1,
        backupA: item.backupB,
        orderId: item.id,
        backupC:this.data.type,
        backupD:1,
        adds:2,
        userId:this.data.userInfo.id,
        body:'顺风车发布保证金'
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: function (res) {
        if (res.data.success) {
          that.requestPayment(res.data.data);
        } else {
          that.setData({
            canSubmit: true
          })
        }
      }
    })
  },
  requestPayment: function (obj) {
    var that = this;
    wx.requestPayment({
      'timeStamp': obj.timeStamp,
      'nonceStr': obj.nonceStr,
      'package': obj.package,
      'signType': obj.signType,
      'paySign': obj.paySign,
      'success': function (res) {
        wx.setStorage({
          key: 'url',
          data: '/pages/freeRideHome/freeRideHome',
        })
        wx.redirectTo({
          url: '/pages/regsuccess/regsuccess?btnText=返回首页&showText=发布成功'
        })
      },
      'fail': function (res) {
        wx.showModal({
          title: '提示',
          content: '支付失败',
          showCancel:false,
          success: function (res) {
            if (res.confirm) {
              that.setData({
                canSubmit:true
              })
            }
          }
        })
      }
    })
  },
  /**
  * 生命周期函数--监听页面初次渲染完成
  */
  onReady: function () {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})